package base.web.tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import org.springframework.context.support.StaticApplicationContext;

public class WebUtils {
    public static final String TEMP_DIR_CONTEXT_ATTRIBUTE = "javax.servlet.context.tempdir";
    public static String CODE_TYPE = "UTF-8";

    /**
     * 获取HttpServletRequest对象
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        return (HttpServletRequest) ServletActionContext.getRequest();
    }

    /**
     * 获取HttpServletResponse对象
     *
     * @return HttpServletResponse
     */
    public static HttpServletResponse getResponse() {
        return (HttpServletResponse) ServletActionContext.getResponse();
    }

    /**
     * 获取Cookie对象
     *
     *
     * @param request
     * @param name Cookie名字
     * @return Cookie
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie cookies[] = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                System.out.println(cookies[i].getName());
                if (name.equals(cookies[i].getName())) {
                    return cookies[i];
                }
            }
        }
        return null;
    }

    public static String getParamter(String name) {
        HttpServletRequest request = getRequest();
        return request.getParameter(name);
    }

    public static String[] getParameterValues(String name) {
        HttpServletRequest request = getRequest();
        return request.getParameterValues(name);
    }

    /**
     * 获取临时目录
     *
     * @param servletContext
     * @return
     */
    public static File getTempDir(ServletContext servletContext) {
        return (File) servletContext.getAttribute(TEMP_DIR_CONTEXT_ATTRIBUTE);
    }

    /**
     * 获取制定路径的实际路径
     *
     * @param servletContext
     * @param path
     * @return
     * @throws java.io.FileNotFoundException
     */
    public static String getRealPath(ServletContext servletContext, String path)
            throws FileNotFoundException {

        // Interpret location as relative to the web application root directory.
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        String realPath = servletContext.getRealPath(path);
        if (realPath == null) {
            throw new FileNotFoundException("未找到文件:" + path);
        }
        return realPath;
    }

    /**
     * 获取Session的值
     *
     * @param name
     * @return
     */
    public static Object getSession(String name) {
        HttpServletRequest request = getRequest();
        HttpSession session = request.getSession(false);
        return (session != null ? session.getAttribute(name) : null);
    }

    /**
     * 设置Session的值
     *
     * @param name
     * @param value
     */
    public static void setSession(String name, Object value) {
        HttpServletRequest request = getRequest();
        if (value != null) {
            request.getSession().setAttribute(name, value);
        } else {
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.removeAttribute(name);
            }
        }
    }
     public static String getMapByKey(Map mapParam, String key) {
        Object val = mapParam.get(key);
        if (val instanceof String)
            return val.toString();
        String retStr = "";
        if (val != null) {
            if (val instanceof Timestamp) //定义格式并转化成字符型日期格式
                retStr = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Timestamp(((Timestamp) val).getTime()));
            if (val instanceof java.sql.Date) //定义格式并转化成字符型日期格式
                retStr = (new SimpleDateFormat("yyyy-MM-dd")).format(val);
            if (val instanceof BigDecimal)
                retStr = val.toString();
        }
        return retStr.trim();
    }
    /**
     * 获取前台提交的参数
     *
     * @return
     */
    public static Map getParameterMap() {
        HttpServletRequest request = getRequest();
        Map parametersMap = new HashMap();
        Enumeration paramters = request.getParameterNames();
        while (paramters.hasMoreElements()) {
            String name = (String) paramters.nextElement();
            String[] values = request.getParameterValues(name);
            String value = "";
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    value += values[i] + ',';
                }
                value = value.substring(0, value.length() - 1);
            }
            parametersMap.put(name, value.trim());
        }
        return parametersMap;
    }

   
  
    /**
     * 获取组织机构编号
     *
     * @return
     */
    public static Long getOrganizeId() {
        return new Long(String.valueOf("22726"));// TODO 暂写死
        /**
         // TODO Auto-generated method stub
         Cookie cookie = getCookie("organizeId");
         if (cookie != null) {
         return new Long(cookie.getValue());
         }
         return null;
         */
    }

    /**
     * 获取组织机构代码
     *
     * @return
     */
    public static Long getOrganizeCode() {
        return new Long(String.valueOf("410927"));// TODO 暂写死
        /*
		// TODO Auto-generated method stub
		Cookie cookie = getCookie("organizeCode");
		if (cookie != null) {
			return new Long(cookie.getValue());
		}
		return null;
		*/
    }

    /**
     * 获取组织机构代码
     *
     * @return
     */
    public static String getOrganizeName() {
        return "台前县";// TODO 暂写死
        /*
		// TODO Auto-generated method stub
		Cookie cookie = getCookie("organizeCode");
		if (cookie != null) {
			return new Long(cookie.getValue());
		}
		return null;
		*/
    }

    /**
     * 获取机构序列
     *
     * @return
     */
    public static String getOrganizeSeq() {
        return "0.1.10.22726.";
    }

    /**
     * 获取机构级别
     *
     * @return
     */
    public static int getFlevel() {
        return 3;
    }

    /**
     * 获取组织机构县区代码（试点县）
     *
     * @return
     */
    public static Long getCountyCode() {
        return new Long(String.valueOf("410927"));// TODO 暂写死
        /*
		// TODO Auto-generated method stub
		Cookie cookie = getCookie("organizeCode");
		if (cookie != null) {
			return new Long(cookie.getValue());
		}
		return null;
		*/
    }

    /**
     * 获取组织机构县区名称 （试点县）
     *
     * @return
     */
    public static String getCountyName() {
        return "台前县";// TODO 暂写死
    }


    /**
     * 获取登录用户名称
     *
     * @return
     */
    public static String getUserName() {
        return "sa"; // TODO 暂写死

    }

    /**
     * 获取登录用户代码
     *
     * @return
     */
    public static Long getUserCode() {
        return new Long("410927999");// TODO 暂写死
        /**
         // TODO Auto-generated method stub
         Cookie cookie = getCookie("getUserCode");
         if (cookie != null) {
         return new Long(cookie.getValue());
         }
         return null;
         */
    }
    /**
     * 获取登录用户代码
     *
     * @return
     */
    public static Long getUserId() {
        return new Long("200");// TODO 暂写死
        /**
         // TODO Auto-generated method stub
         Cookie cookie = getCookie("getUserCode");
         if (cookie != null) {
         return new Long(cookie.getValue());
         }
         return null;
         */
    }

    /**
     * 获取参合年度
     *
     * @return
     */
    public static int getJCMYear() {
        return 2011; // TODO 暂写死
    }

    /**
     * 医疗机构ID
     *
     * @return
     */
    public static Long getMOrganizeId() {
        return new Long("41768");// TODO 暂写死
    }

    /**
     * 医疗机构编码
     *
     * @return
     */
    public static Long getMOrganizeCode() {
        return new Long("41092702000001"); // TODO 暂写死
    }

    /**
     * 医疗机构名称
     *
     * @return
     */
    public static String getMOrganizeName() {
        return "夹河乡卫生院";    // TODO 暂写死
    }

    /**
     * 医疗机构所属行政区域ID
     *
     * @return
     */
    public static Long getMCountyId() {
        return new Long(String.valueOf("39491")); // TODO 暂写死
    }

    /**
     * 医疗机构所属行政区域编码
     *
     * @return
     */
    public static Long getMCountyCode() {
        return new Long(String.valueOf("41092702")); // TODO 暂写死
    }

    /**
     * 医疗机构所属行政区域名称
     *
     * @return
     */
    public static String getMCountyName() {
        return "夹河乡"; // TODO 暂写死
    }

    /**
     * URL解码
     *
     * @param source
     * @return
     */
    public static String decode(String source) {
        try {
            return java.net.URLDecoder.decode(source, CODE_TYPE);
        } catch (UnsupportedEncodingException e) {
            return "";
        } catch (NullPointerException e) {
            return "";
        }
    }

    /**
     * 复制map对象中的值
     *
     * @param map    接受第二个参数中map的值
     * @param mapAdd 需要取值的map对象
     */
    public static void mapCopy(Map map, Map mapAdd) {
        if (map == null)
            map = new HashMap();
        if (mapAdd == null)
            return;

        Iterator it = mapAdd.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            map.put(key, mapAdd.get(key) != null ? mapAdd.get(key) : "");

        }
    }


}
